package com.example.controllers;

import com.example.common.ResultResponse;
import com.example.common.ErrorCode;
import com.example.common.exception.ResourceConflictException;
import com.example.common.exception.ResourceNotFoundException;
import com.example.common.exception.UnsupportedMediaTypeException;
import com.example.dtos.plugin.*;
import com.example.services.PluginService;
import com.example.common.dto.PageRequestDTO;
import com.example.common.dto.PaginationDTO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;

/**
 * 插件管理控制器
 */
@RestController
@RequestMapping("/api/v1/plugins")
@Tag(name = "插件管理", description = "插件的上传、查询、启用/禁用和删除")
public class PluginController {

    @Autowired
    private PluginService pluginService;
    
    /**
     * 获取插件列表
     *
     * @param pageRequest 分页请求
     * @param status 插件状态筛选：all(全部)/enabled(已启用)/disabled(已禁用)
     * @param keyword 搜索关键词，搜索插件名称、ID或描述
     * @return 插件分页列表
     */
    @GetMapping
    @Operation(summary = "获取插件列表", description = "获取系统中的插件列表，支持分页、筛选和搜索")
    public ResponseEntity<ResultResponse<PaginationDTO>> getPluginList(
            @Valid PageRequestDTO pageRequest,
            @Parameter(description = "插件状态筛选：all(全部)/enabled(已启用)/disabled(已禁用)")
            @RequestParam(required = false, defaultValue = "all") String status,
            @Parameter(description = "搜索关键词，搜索插件名称、ID或描述")
            @RequestParam(required = false) String keyword) {
        PaginationDTO pageData = pluginService.getPluginList(pageRequest, status, keyword);
        return ResponseEntity.ok(ResultResponse.success(pageData));
    }
    
    /**
     * 获取插件详情
     *
     * @param pluginId 插件ID
     * @return 插件详情
     */
    @GetMapping("/{pluginId}")
    @Operation(summary = "获取插件详情", description = "获取特定插件的详细信息")
    public ResponseEntity<ResultResponse<PluginDetailDTO>> getPluginDetail(
            @PathVariable @Parameter(description = "插件ID") String pluginId) {
        PluginDetailDTO plugin = pluginService.getPluginDetail(pluginId);
        return ResponseEntity.ok(ResultResponse.success(plugin));
    }
    
    /**
     * 上传插件
     *
     * @param file 插件包文件
     * @param autoActivate 是否自动启用
     * @return 上传结果
     */
    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传插件", description = "上传新的插件包到系统")
    public ResponseEntity<ResultResponse<PluginUploadResponseDTO>> uploadPlugin(
            @RequestParam("file") @Parameter(description = "插件包文件，支持.jar或.zip格式") MultipartFile file,
            @RequestParam(value = "autoActivate", defaultValue = "false") 
            @Parameter(description = "上传后是否自动启用") boolean autoActivate) {
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null ||
                (!contentType.equals("application/java-archive") &&
                 !contentType.equals("application/zip") &&
                 !contentType.equals("application/x-zip-compressed"))) {
            throw new UnsupportedMediaTypeException(
                    contentType, "application/java-archive", "application/zip");
        }

        PluginUploadResponseDTO result = pluginService.uploadPlugin(file, autoActivate);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(ResultResponse.success(result));
    }
    
    /**
     * 更新插件状态
     *
     * @param pluginId 插件ID
     * @param statusDTO 状态更新请求
     * @return 更新结果
     */
    @PatchMapping("/{pluginId}/status")
    @Operation(summary = "启用/禁用插件", description = "修改插件的启用状态")
    public ResponseEntity<ResultResponse<PluginStatusResponseDTO>> updatePluginStatus(
            @PathVariable @Parameter(description = "插件ID") String pluginId,
            @RequestBody @Valid PluginStatusDTO statusDTO) {
        PluginStatusResponseDTO result = pluginService.updatePluginStatus(pluginId, statusDTO);
        return ResponseEntity.ok(ResultResponse.success(result));
    }
    
    /**
     * 删除插件
     *
     * @param pluginId 插件ID
     * @param force 是否强制删除
     * @return 删除结果
     */
    @DeleteMapping("/{pluginId}")
    @Operation(summary = "删除插件", description = "从系统中删除指定插件")
    public ResponseEntity<ResultResponse<Void>> deletePlugin(
            @PathVariable @Parameter(description = "插件ID") String pluginId,
            @RequestParam(value = "force", defaultValue = "false") 
            @Parameter(description = "是否强制删除") boolean force) {
        pluginService.deletePlugin(pluginId, force);
        return ResponseEntity.ok(ResultResponse.<Void>success(null));
    }
} 